package 掘金.简单四则运算;

import java.util.Deque;
import java.util.LinkedList;

public class Main {

    private static int cal(int a,char op, int b){
        switch (op) {
            case '+': return a+b;
            case '-': return a-b;
            case '/': return a/b;
            case '*': return a*b;
        }
        return 0;
    }

    public static int solution(String expression) {
        // Please write your code here
        Deque<Integer> numStack = new LinkedList<>();
        Deque<Character> opStack = new LinkedList<>();

        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if(c >= '0' && c<= '9'){
                numStack.push(c-'0');
            }else{
                if(c == '(')
                    opStack.push(c);
                else if(c==')'){
                    while (opStack.peek()!='(') {
                        char op = opStack.pop();
                        int b = numStack.pop();
                        int a = numStack.pop();
                        numStack.push(cal(a, op, b));
                    }
                    opStack.pop();
                }else {
                    // 弹出栈中优先级高于或等于当前运算符的所有运算符
                    switch (c) {
                        case '+':
                        case '-':
                            while (!opStack.isEmpty()&&opStack.peek()!='(') {
                                char op = opStack.pop();
                                int b = numStack.pop();
                                int a = numStack.pop();
                                numStack.push(cal(a, op, b));
                            }
                            break;
                        case '*':
                        case '/':
                            while (!opStack.isEmpty()&&(opStack.peek()=='*'|| opStack.peek()=='/')) {
                                char op = opStack.pop();
                                int b = numStack.pop();
                                int a = numStack.pop();
                                numStack.push(cal(a, op, b));
                            }
                            break;
                    }
                    // 将当前运算符入栈
                    opStack.push(c);

                }
            }
        }
        // 将运算符号依次弹出
        while (!opStack.isEmpty()) {
            char op = opStack.pop();
            int b = numStack.pop();
            int a = numStack.pop();
            numStack.push(cal(a, op, b));
        }


        return numStack.pop();
    }

    public static void main(String[] args) {
        // You can add more test cases here
        //System.out.println(solution("1+1") == 2);
        System.out.println(solution("(1+(4+5+2)-3)+(6+8)") == 23);
    }
}